package view;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Shape;
import java.text.AttributedCharacterIterator;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JWindow;
import javax.swing.SwingConstants;
import javax.swing.Timer;

import blink.model.Experiment;
import blink.model.Stimulus;
import blink.model.Target;
import blink.model.Task;
import blink.model.Trial;
import java.awt.Image;
import javax.swing.JButton;

import org.w3c.dom.ls.LSInput;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.ImageObserver;

public class WindowDiaporama2 extends JWindow implements Runnable,	ActionListener {

	private Experiment experience = new Experiment();
	private List<Trial> listeDesEssais;

	private Task uneTache = new Task();

	private List<Stimulus> listesdestimulus;
	private Stimulus[] tableaudestimulus;
	private Stimulus unStimulus;
	private List<Target> listesDeTarget;
	private Target uneTarget;
	private Image img;
	private List<Trial> listedetrial;
	private Trial unEssai;
	private List<Task> listeTask;
	JPanel ensembleImage = new JPanel();

	private JImagePanel imagePanel = new JImagePanel();
	private JPanel image = new JPanel();

	private JPanel panNoir = new JPanel();
	private JPanel question = new JPanel();
	JButton imageB = new JButton();
	JButton boutonOui = new JButton("Oui");
	JButton boutonNon = new JButton("Non");
	JButton boutonNoAnwser = new JButton("Je ne sais pas.");

	int StimulusSize;
	int nbButton = 0;

	Timer timer;
	
	int reponseUtilisateur = 0;
	//reponse aux questions
	public final static int NO=-1;
    public final static int YES=-2;
    public final static int NO_ANSWER=-3;

	int arretThread = 0;

	public WindowDiaporama2(Experiment experience) {
		getContentPane().setBackground(Color.BLACK);
		repaint();
		setVisible(true);

		this.experience = experience;

		// On recupere la taille de l'ecran
		Dimension tailleEcran = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
		int hauteur = (int) tailleEcran.getHeight();
		int largeur = (int) tailleEcran.getWidth();

		// On donne a la jWindow la taille de l 'ecran
		setSize(largeur, hauteur);
		setLocationRelativeTo(null);
		// imagePanel.setStretch(true);

		image.setBackground(Color.BLACK);
		ensembleImage.setBackground(Color.BLACK);
		question.setLayout(new BorderLayout());

		// On ajout l'imagePanel à la fenetre
		getContentPane().add(image);

		// On lance un nouveau Thread
		new Thread(this).start();

	}

	@Override
	public synchronized void run() {
		// TODO Auto-generated method stub
		try {
			//On affiche le diaporama et on pose la question
			affichestimulus();
			
			// On propose d'enregistere les resultats
			//EnregistrementResultat monEnregistrement = new EnregistrementResultat(experience);
			
			//On ferme cette la JWindows
			this.setVisible(false);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	
										/////////////////////////////////////////
	
	
	
	
	public synchronized void affichestimulus() throws InterruptedException {
		
		// on recupere le nb d'essai
		listeDesEssais = experience.getTrials();

		listeTask = experience.getTasks();
		
		
		boolean typeQuestion = false;
		
		int displayTime = 0;
		int lagTime = 0;

		for (int a = 0; a <= listeDesEssais.size() - 1; a++) {

			Stimulus[] listeStimulus = new Stimulus[listeDesEssais.get(a).getSequence().length];
			listeStimulus = listeDesEssais.get(a).getSequence();

			for (int b = 0; b <= listeTask.size() - 1; b++) {

				displayTime = listeTask.get(b).getDisplayTime();
				lagTime = listeTask.get(b).getLagTime();
				List<Target> t = listeTask.get(b).getTargets();
				typeQuestion = t.get(b).isDetected();

				// on recupere la taille des stimulus
				StimulusSize = listeTask.get(b).getStimulusSize();

				System.out.println("TYPE : " + typeQuestion);
				System.out.println("StimulusSize : " + StimulusSize);
				
				
				for (int i = 0; i <= listeStimulus.length - 1; i++) {

					image.add(imagePanel);
					getContentPane().removeAll();
					getContentPane().add(image);
					getContentPane().revalidate();
					getContentPane().repaint();

					// on recupere les stimulus
					img = listeStimulus[i].getImg(StimulusSize, -1);
					imagePanel.setImage(img);

					// on change la taille de l'emage panel
					imagePanel.setSize(new Dimension(StimulusSize, StimulusSize));

					// On centre l'image panel
					int panelX = (getWidth() - imagePanel.getWidth() - getInsets().left - getInsets().right) / 2;
					int panelY = ((getHeight() - imagePanel.getHeight() - getInsets().top - getInsets().bottom) / 2);
					imagePanel.setLocation(panelX, panelY);

					imagePanel.repaint();

					// le temps que l'image va rester à l'écran
					Thread.sleep(displayTime);


					// delai entre deux images
					getContentPane().removeAll();
					panNoir.setBackground(Color.BLACK);
					getContentPane().add(panNoir);
					getContentPane().revalidate();
					getContentPane().repaint();
					Thread.sleep(lagTime);

				}

				// On pose une question par cible dans la task
				for (int c = 0; c <= t.size() - 1; c++) {

					String ques = t.get(c).getQuestion();
					typeQuestion = t.get(c).isDetected();

					// methode qui permet a l'utilisateur de répondre à la  question
					if (typeQuestion == false) {
						// type identifié  On passe la target dans la methode qui gere la  question
						identifie(listeTask, t.get(c));

					} else if (typeQuestion == true) {
						// type detecté
						detecte(listeTask, ques);
					}
					
					listeDesEssais.get(a).setUserResponse(c, reponseUtilisateur);

				}

			}


		}

	}

											/////////////////////////////////////////
	
	
	// //////////////////////////////////////////////////////////////
	// Gestion de la question si la target est de type identifie
	////////////////////////////////////////////////////////////////
	public void  identifie(List<Task> listeT, Target target)
			throws InterruptedException {

		question.removeAll();
		nbButton = 0;
		String ques = target.getQuestion();

		// listeDesEssais = experience.getTrials();
		// for (int b = 0; b <= listeTask.size() - 1; b++) {

		// On affiche toutes le image qui serve de cible
		for (int i = 0; i <= listeT.size() - 1; i++) {

			List<Target> listeTarget = listeT.get(i).getTargets();
			List<Stimulus> listeS = listeTarget.get(i).getPossibleTargets();

			System.out.println("TAILLE" + listeS.size());

			for (int j = 0; j <= listeS.size() - 1; j++) {


				ImageIcon ima = new ImageIcon(listeS.get(j).getImg(200, 200));
				imageB = new JButton(ima);
				imageB.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						// getButton(e);

						System.out.println("IDENTIFIE");
						// ici, c'est l'id de l'image qui est recupere
						String name = ((JButton) e.getSource()).getName();
						System.out.println(name);
						
						
						reponseUtilisateur = Integer.parseInt(name);
						
						//On redemare le thread
						redemareThread();

					}
				});
				imageB.setName(String.valueOf(j));
				imageB.setBackground(Color.BLACK);
				ensembleImage.add(imageB);
				nbButton++;
			}

		}
		question.add(ensembleImage, BorderLayout.NORTH);
		// getContentPane().removeAll();
		question.setBackground(Color.BLACK);
		// on affiche le texte
		JLabel q = new JLabel(ques, JLabel.CENTER);
		q.setForeground(new Color(223, 223, 223));
		question.add(q, BorderLayout.CENTER);

		getContentPane().removeAll();
		question.setBackground(Color.BLACK);
		getContentPane().add(question);
		getContentPane().revalidate();
		getContentPane().repaint();


		//On arrete le thread en attendant la reponse
		arretThread();
		

	}
	
	
	////////////////////////////////////////////////////////////////////
	

//	private void getButton(ActionEvent e) {
//		// TODO Auto-generated method stub
//		if (e.getSource() == imageB) {
//			System.out.println("IDENTIFIE");
//			// ici, c'est l'id de l'image qui est recupere
//			String name = ((JButton) e.getSource()).getName();
//			System.out.println(name);
//		}
//		
//		//On redemare le thread
//		redemareThread();
//	}
	
	
	////////////////////////////////////////////////////////////////////
	

	// Gestion de la question si la target est de type detecte
	public void detecte(List<Task> listeTask, String ques)
			throws InterruptedException {

		question.removeAll();

		listeDesEssais = experience.getTrials();
		for (int b = 0; b <= listeTask.size() - 1; b++) {

			List<Target> listeF = listeTask.get(b).getTargets();

			for (int i = 0; i <= listeF.size() - 1; i++) {

				// on recupere les stimulus
				List<Stimulus> listeTarget = listeF.get(i).getPossibleTargets();

				for (int j = 0; j <= listeTarget.size() - 1; j++) {

					ImageIcon monimage = new ImageIcon(listeTarget.get(j)
							.getImg(300, 300));
					JLabel image = new JLabel(monimage, SwingConstants.CENTER);
					image.setName(String.valueOf(i));
					question.add(image, BorderLayout.NORTH);

					getContentPane().removeAll();
					question.setBackground(Color.BLACK);
					getContentPane().add(question);
					getContentPane().revalidate();
					getContentPane().repaint();
				}

				// img = listeStimulus[i].getImg(StimulusSize, -1);
				// question.setImage(img);
				// question.repaint();
				// getContentPane().add(question);
			}
			// on affiche le texte
			JLabel q = new JLabel(ques, JLabel.CENTER);
			q.setForeground(new Color(223, 223, 223));
			question.add(q, BorderLayout.CENTER);

			JPanel panQ = new JPanel();
			panQ.add(boutonOui);
			panQ.add(boutonNon);
			panQ.add(boutonNoAnwser);
			panQ.setBackground(new Color(0, 0, 0));
			question.add(panQ, BorderLayout.SOUTH);

			getContentPane().removeAll();
			question.setBackground(Color.BLACK);
			getContentPane().add(question);
			getContentPane().revalidate();
			getContentPane().repaint();

			boutonOui.addActionListener((ActionListener) this);
			boutonNon.addActionListener((ActionListener) this);
			boutonNoAnwser.addActionListener((ActionListener) this);
			
			//On arrete le thread en attendant la reponse
			arretThread();
			
			
		}



	}
	
	
	////////////////////////////////////////////////////////////////////
	
	

	// evenement de la reponse du type d'image detecte
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == boutonOui) {
			
			reponseUtilisateur = YES;
			System.out.println("OUI");
			
		} else if (e.getSource() == boutonNon) {
			
			reponseUtilisateur = NO;
			System.out.println("NON");
			
		} else if (e.getSource() == boutonNoAnwser) {
			
			reponseUtilisateur = NO_ANSWER;
			System.out.println("boutonNoAnwser");
			
		}
		
		//On redemare le thread
		redemareThread();

	}
	
	
	////////////////////////////////////////////////////////////////////
	

	public void redemareThread() {

		// On redemare le thread arrété
		synchronized (this) {
			arretThread = 1;
			this.notify();
			System.out.println("on clique " + arretThread);
		}
	}
	

	////////////////////////////////////////////////////////////////////

	
	public void arretThread() {
		arretThread = 0;
		//On met le thread en attente de la reponse
		synchronized(this) {
			while (arretThread == 0) {
				try {
				System.out.println("on boucle " + arretThread);
				this.wait(); 
				} catch (InterruptedException ie) {

					System.out.println("exeption");

				} } }
		
	}
	
	///////////////////////////////////////////////////////////////////
	

}
